#!/bin/bash
# origin by Anthony Liguori, modified by fjrti@163.com

BRIDGE=br-toy

# Network information
NETWORK=192.168.10.0
NETMASK=255.255.255.0
GATEWAY=192.168.10.253
DHCPRANGE=192.168.10.1,192.168.10.50

check_bridge() {
    if ip link show | grep "^[0-9]\+: $1:" &> /dev/null; then
        return 1
    else
        return 0
    fi
}

create_bridge() {
    ip link add name "$1" type bridge
    ip link set "$1" type bridge stp 0
    ip addr add "$GATEWAY/$NETMASK" dev "$1"
    ip link set "$1" up
}

enable_ip_forward() {
    echo 1 > /proc/sys/net/ipv4/ip_forward
}

add_filter_rules() {
    iptables -t nat -A POSTROUTING -s "$NETWORK/$NETMASK" ! -d "$NETWORK/$NETMASK" -j MASQUERADE
}

start_dnsmasq() {
    dnsmasq \
        --strict-order \
        --except-interface=lo \
        --interface=$BRIDGE \
        --listen-address=$GATEWAY \
        --bind-interfaces \
        --dhcp-range=$DHCPRANGE \
        --dhcp-range=::1,::400,constructor:eth0 \
        --enable-ra \
        --conf-file="" \
        --pid-file=/var/run/dnsmasq-$BRIDGE.pid \
        --dhcp-leasefile=/var/run/dnsmasq-$BRIDGE.leases \
        --dhcp-no-override
}

setup_bridge_nat() {
    if check_bridge "$1" ; then
        create_bridge "$1"
        enable_ip_forward
        add_filter_rules "$1"
        start_dnsmasq "$1"
    fi
}

setup_bridge_vlan() {
    if check_bridge "$1" ; then
        create_bridge "$1"
        start_dnsmasq "$1"
    fi
}

setup_bridge_nat "$BRIDGE"

if test "$1" ; then
    ip addr flush dev "$1"
    ip link set "$1" up
    ip link set "$1" master "$BRIDGE"
fi
